package renderer.program;

import java.nio.FloatBuffer;

import math.MatrixUtil;

import org.lwjgl.opengl.GL20;

import world.Camera;
import game.WorldManager;

public class GLProgramManager {
	public static GLProgramManager getInstance() {
		if (instance == null) {
			instance = new GLProgramManager();
		}
		return instance;
	}

	public static void init() throws Exception {
		getInstance()._init();
	}

	public static void resized(int width, int height) {
		getInstance()._resized(width, height);
	}


	public static BaseGLProgram getBaseProgram() {
		return getInstance().baseProgram;
	}

	public static LineGLProgram getLineProgram() {
		return getInstance().lineGLProgram;
	}

	// ----------------------------------------------------------------private
	private static GLProgramManager instance;
	private BaseGLProgram baseProgram;
	private LineGLProgram lineGLProgram;

	private GLProgramManager() {
	}

	public void _init() throws Exception {
		baseProgram = new BaseGLProgram();
		baseProgram.init();

		lineGLProgram = new LineGLProgram();
		lineGLProgram.init();
	}

	public void _resized(int width, int height) {
		Camera camera = WorldManager.getCamera();
		FloatBuffer projectionMatrixBuffer = MatrixUtil.toBuffer(WorldManager.getCamera().getProjectionMatrix());

		baseProgram.begin();
		{
			GL20.glUniformMatrix4(baseProgram.getProjectionMatrixUniform(), false, projectionMatrixBuffer);
		}
		baseProgram.end();

		lineGLProgram.begin();
		{
			GL20.glUniformMatrix4(lineGLProgram.getProjectionMatrixUniform(), false, projectionMatrixBuffer);
			GL20.glUniformMatrix4(lineGLProgram.getCameraMatrixUniform(), false, camera.calcLookAtMatrix().toBuffer());

		}
		lineGLProgram.end();
	}
}
